package com.autotest.sync.utils;

import java.io.OutputStream;
import java.io.PrintStream;

import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 * 用于打印相关日志
 * @author thomas.ning
 * @version 2017年8月1日 下午1:45:55
 */
public class MyPrintStream extends PrintStream {
	private JTextArea textArea;

	public MyPrintStream(OutputStream out, JTextArea text) {
		super(out);
		textArea = text;
		lineListener();

	}

	@Override
	public void write(byte[] buf, int off, int len) {
		final String message = new String(buf, off, len);
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				textArea.append(message);

			}
		});

	}

	/**
	 * 注册文本区域插入监听
	 */
	private void lineListener() {
		textArea.getDocument().addDocumentListener(new DocumentListener() {
			@Override
			public void insertUpdate(DocumentEvent e) {
				SwingUtilities.invokeLater(new Runnable() {
					@Override
					public void run() {
						if (textArea.getLineCount() >= 1000) {
							int end = 0;
							try {
								end = textArea.getLineEndOffset(100);
							} catch (Exception e) {
							}
							textArea.replaceRange("", 0, end);
						}
						textArea.setCaretPosition(textArea.getText().length());
					}
				});
			}

			@Override
			public void removeUpdate(DocumentEvent e) {

			}

			@Override
			public void changedUpdate(DocumentEvent e) {

			}
		});
	}

}
